import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';

import '../../config/loading_toast.dart';

class AssetImgUtils {
  AssetImgUtils(_);

  static downloadImgToAlbum(String imgUrl) async {
    List<String> imgList = imgUrl.split('/');
    var response = await Dio()
        .get(imgUrl, options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaver.saveImage(
        Uint8List.fromList(response.data),
        name: imgList.last);
    getSaveResult(result);
  }

  static downloadFileToAlbum(String imgUrl) async {
    List<String> imgList = imgUrl.split('/');
    String savePath = (await getTemporaryDirectory()).path;
    debugPrint('保存路径$savePath');
    await Dio().download(
      imgUrl,
      savePath + imgList.last,
    );
    final result =
        await ImageGallerySaver.saveFile(savePath, isReturnPathOfIOS: true);
    getSaveResult(result);
  }

  static downloadVideoToAlbum(String imgUrl) async {
    List<String> imgList = imgUrl.split('/');
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + imgList.last;
    await Dio().download(imgUrl, savePath, onReceiveProgress: (count, total) {
      debugPrint("${(count / total * 100).toStringAsFixed(0)}%");
    });
    final result = await ImageGallerySaver.saveFile(savePath);
    getSaveResult(result);
  }

  static getSaveResult(result) {
    if (result != null && result['isSuccess'] == true) {
      toast('已成功保存到相册');
    } else {
      toast('保存失败');
    }
    debugPrint(result.toString());
  }
}
